#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简单的简历上传处理演示

模拟前端文件上传处理流程
"""

import os
import json
import tempfile
from typing import Dict, Any

def mock_file_upload_handler(file_content: str, filename: str) -> Dict[str, Any]:
    """
    模拟处理上传的简历文件
    
    Args:
        file_content: 文件内容
        filename: 文件名
        
    Returns:
        Dict: 处理结果
    """
    
    try:
        # 验证文件
        if not filename:
            return {
                'success': False,
                'message': '文件名无效',
                'error_code': 'INVALID_FILENAME'
            }
        
        file_extension = os.path.splitext(filename.lower())[1]
        allowed_extensions = {'.pdf', '.doc', '.docx', '.txt'}
        
        if file_extension not in allowed_extensions:
            return {
                'success': False,
                'message': f'不支持的文件格式。支持格式: {", ".join(allowed_extensions)}',
                'error_code': 'UNSUPPORTED_FORMAT'
            }
        
        if not file_content or len(file_content.strip()) == 0:
            return {
                'success': False,
                'message': '文件内容为空',
                'error_code': 'EMPTY_CONTENT'
            }
        
        # 解析关键信息
        key_info = extract_simple_resume_info(file_content)
        
        # 构建成功响应
        return {
            'success': True,
            'message': '简历解析成功',
            'data': {
                'file_info': {
                    'original_filename': filename,
                    'file_extension': file_extension,
                    'content_length': len(file_content)
                },
                'raw_content': file_content,
                'key_info': key_info
            }
        }
        
    except Exception as e:
        return {
            'success': False,
            'message': f'处理失败: {str(e)}',
            'error_code': 'PROCESSING_ERROR'
        }

def extract_simple_resume_info(content: str) -> Dict[str, Any]:
    """
    简单的简历信息提取
    
    Args:
        content: 简历文本内容
        
    Returns:
        Dict: 提取的关键信息
    """
    import re
    
    content_lower = content.lower()
    
    # 提取工作经验
    experience_years = 0
    exp_patterns = [
        r'(\d+)\s*年.*?经验',
        r'经验.*?(\d+)\s*年',
        r'工作.*?(\d+)\s*年'
    ]
    
    for pattern in exp_patterns:
        match = re.search(pattern, content)
        if match:
            experience_years = int(match.group(1))
            break
    
    # 提取技能
    tech_skills = []
    skill_keywords = [
        'python', 'java', 'javascript', 'react', 'vue', 'angular',
        'django', 'spring', 'flask', 'mysql', 'redis', 'docker',
        'git', 'linux', 'aws', 'kubernetes'
    ]
    
    for skill in skill_keywords:
        if skill in content_lower:
            tech_skills.append(skill.title())
    
    # 提取教育背景
    education = '未识别'
    edu_patterns = [
        r'本科',
        r'学士',
        r'硕士',
        r'博士',
        r'专科',
        r'大学'
    ]
    
    for pattern in edu_patterns:
        if re.search(pattern, content):
            education = pattern
            break
    
    # 提取地点信息
    location = '未识别'
    cities = ['北京', '上海', '深圳', '广州', '杭州', '南京', '武汉', '成都', '西安']
    
    for city in cities:
        if city in content:
            location = city
            break
    
    # 提取期望薪资
    salary = '未识别'
    salary_patterns = [
        r'(\d+)-(\d+)',
        r'(\d+)k',
        r'薪资.*?(\d+)'
    ]
    
    for pattern in salary_patterns:
        match = re.search(pattern, content_lower)
        if match:
            salary = match.group(0)
            break
    
    return {
        'experience_years': experience_years,
        'skills': {
            'all_skills': tech_skills,
            'programming_languages': [s for s in tech_skills if s.lower() in ['python', 'java', 'javascript']],
            'frameworks': [s for s in tech_skills if s.lower() in ['react', 'vue', 'django', 'spring']],
            'databases': [s for s in tech_skills if s.lower() in ['mysql', 'redis']],
            'tools': [s for s in tech_skills if s.lower() in ['git', 'docker', 'linux']]
        },
        'education': education,
        'preferred_location': location,
        'expected_salary': salary,
        'resume_length': len(content)
    }

def demo_api_response_format():
    """演示API响应格式"""
    
    # 模拟简历内容
    test_resume = """
    张三简历
    
    基本信息：
    姓名：张三
    工作经验：3年
    教育：本科计算机科学
    地点：北京
    期望薪资：15000-20000
    
    技能：
    - 编程语言：Python, Java, JavaScript
    - 框架：Django, React, Vue
    - 数据库：MySQL, Redis
    - 工具：Git, Docker, Linux
    
    工作经历：
    2021-2024 软件开发工程师
    - 负责后端开发
    - 参与系统架构设计
    """
    
    # 处理上传
    result = mock_file_upload_handler(test_resume, "张三简历.txt")
    
    # 输出结果
    print("📋 简历上传API响应格式演示")
    print("=" * 50)
    print(json.dumps(result, indent=2, ensure_ascii=False))
    
    return result

def create_api_documentation():
    """创建API文档"""
    
    doc = {
        "api_name": "简历文件上传解析API",
        "version": "1.0.0",
        "description": "接收前端上传的简历文件，解析内容并提取关键信息",
        
        "endpoints": {
            "upload_complete": {
                "url": "/api/resume/upload/",
                "method": "POST",
                "content_type": "multipart/form-data",
                "description": "完整版简历上传解析API",
                "parameters": {
                    "resume_file": {
                        "type": "file",
                        "required": True,
                        "description": "简历文件",
                        "supported_formats": [".pdf", ".doc", ".docx", ".txt"],
                        "max_size": "10MB"
                    }
                },
                "response": {
                    "success": {
                        "type": "boolean",
                        "description": "请求是否成功"
                    },
                    "message": {
                        "type": "string",
                        "description": "处理结果消息"
                    },
                    "data": {
                        "type": "object",
                        "properties": {
                            "file_info": {
                                "original_filename": "string",
                                "file_size": "integer",
                                "file_extension": "string",
                                "content_length": "integer"
                            },
                            "raw_content": "string",
                            "key_info": {
                                "skills": "object",
                                "experience_years": "integer",
                                "education": "string",
                                "preferred_location": "string",
                                "expected_salary": "string"
                            }
                        }
                    }
                }
            },
            
            "upload_simple": {
                "url": "/api/resume/upload/simple/",
                "method": "POST",
                "description": "简化版API，只返回解析后的文本内容"
            }
        },
        
        "error_codes": {
            "NO_FILE_UPLOADED": "未上传文件",
            "INVALID_FILENAME": "文件名无效",
            "UNSUPPORTED_FORMAT": "不支持的文件格式",
            "FILE_TOO_LARGE": "文件过大",
            "EMPTY_FILE": "文件为空",
            "EMPTY_CONTENT": "文件内容为空",
            "PROCESSING_ERROR": "处理失败",
            "INTERNAL_SERVER_ERROR": "服务器内部错误"
        },
        
        "usage_examples": {
            "curl": 'curl -X POST -F "resume_file=@resume.pdf" http://localhost:8000/api/resume/upload/',
            "javascript": """
const formData = new FormData();
formData.append('resume_file', fileInput.files[0]);

fetch('/api/resume/upload/', {
    method: 'POST',
    body: formData
})
.then(response => response.json())
.then(data => {
    if (data.success) {
        console.log('解析成功:', data.data);
    } else {
        console.log('解析失败:', data.message);
    }
});
            """,
            "python": """
import requests

with open('resume.pdf', 'rb') as f:
    files = {'resume_file': f}
    response = requests.post('http://localhost:8000/api/resume/upload/', files=files)
    
if response.status_code == 200:
    data = response.json()
    print('解析结果:', data)
            """
        }
    }
    
    return doc

def main():
    """主演示函数"""
    print("🚀 简历上传API功能演示")
    print("=" * 60)
    
    # 1. 演示API响应格式
    result = demo_api_response_format()
    
    print("\n" + "=" * 60)
    print("📚 API文档")
    print("=" * 60)
    
    # 2. 显示API文档
    doc = create_api_documentation()
    print(json.dumps(doc, indent=2, ensure_ascii=False))
    
    print("\n" + "=" * 60)
    print("✅ 功能说明")
    print("=" * 60)
    
    print("""
📤 API功能特点：
1. 支持多种格式：PDF、Word、TXT文件
2. 智能解析：提取技能、经验、教育背景等关键信息
3. 错误处理：完善的文件验证和错误提示
4. 安全检查：文件大小限制、格式验证
5. 结构化输出：JSON格式，便于前端处理

🔧 使用步骤：
1. 前端选择简历文件
2. 使用FormData封装文件
3. POST请求到API端点
4. 获取JSON格式的解析结果
5. 根据success字段判断处理结果

📋 返回数据包含：
- 文件基本信息（名称、大小、格式）
- 原始文本内容
- 结构化关键信息（技能、经验等）
- 详细的错误信息（如有）

🌐 前端集成：
可以很容易地集成到React、Vue等前端框架中
支持拖拽上传、进度显示等高级功能
    """)

if __name__ == "__main__":
    main()
